package com.joinval.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 高德地图工具类
 *
 * @author shen shuai
 * @create 2024-09-26 下午 2:50
 */
@Slf4j
@UtilityClass
public class GaodeUtils {

    /**
     * 根据地址获取经纬度
     *
     * @param address 地址
     * @return 经纬度和区
     */
    public Map<String, String> getgeocodes(String address, String countyName) {
        String requestUrl = String.format(
                "https://restapi.amap.com/v3/geocode/geo?key=a6f2701951181e539f656741fc08671d&output=JSON&city=%s&address=%s",
                "上海",
                address.replaceAll(" ", "")
                        .replace("#", "")
                        .replace("、", "")
                        .replace("|", "")
                        .replace("(", "")
                        .replace(")", "")
        );

        if (requestUrl == null) {
            return null;
        }

        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(requestUrl).openStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
        } catch (Exception e) {
            // e.printStackTrace();
            log.error("根据地址获取经纬度请求失败!");
            return null;
        }

        JSONObject jsonObject = JSON.parseObject(response.toString());
        JSONArray geocodesArray = jsonObject.getJSONArray("geocodes");

        if (geocodesArray != null && !geocodesArray.isEmpty()) {
            Map<String, String> map = new HashMap<>();

            for (int i = 0; i < geocodesArray.size(); i++) {
                JSONObject geocode = geocodesArray.getJSONObject(i);
                String location = geocode.getString("location");
                String district = geocode.getString("district");

                // 只当县区名相同才存入 Map
                if (countyName != null && countyName.equals(district)) {
                    if (location != null && location.contains(",")) {
                        String[] lngLat = location.split(",");
                        map.put("lng", lngLat[0]);
                        map.put("lat", lngLat[1]);
                    }
                    map.put("district", district);
                    return map;
                }
                if (StringUtils.isEmpty(countyName)) {
                    if (location != null && location.contains(",")) {
                        String[] lngLat = location.split(",");
                        map.put("lng", lngLat[0]);
                        map.put("lat", lngLat[1]);
                    }
                    map.put("district", district);
                    return map;
                }
            }
        }

        return null;
    }

    /**
     * 根据经纬度获取街镇
     *
     * @param latAndLng 经纬度
     * @return 街镇
     */
    public static Map<String, String> getAddressComponent(String latAndLng) {
        // 构造请求地址
        String requestUrl = String.format("https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=%s&key=a6f2701951181e539f656741fc08671d&radius=&extensions=all&roadlevel=0", latAndLng);
        StringBuilder response = new StringBuilder();

        try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(requestUrl).openStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
        } catch (Exception e) {
            log.error("根据经纬度获取街镇请求失败!");
            return null;
        }

        // 解析 JSON 响应
        JSONObject jsonObject = JSON.parseObject(response.toString());

        // 检查响应是否合法
        if ("1".equals(jsonObject.getString("status"))) {
            JSONObject regeocode = jsonObject.getJSONObject("regeocode");
            if (regeocode != null) {
                JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
                if (addressComponent != null) {
                    Map<String, String> resultMap = new HashMap<>();
                    // 获取街镇名称
                    String township = addressComponent.getString("township");
                    if (township != null) {
                        resultMap.put("township", township);
                    }
                    return resultMap;
                }
            }
        }

        return null;
    }
}
